#include "LoggerWindow.h"
#include <cstdarg>
#include <cstdio>
using namespace std;

QWidget* LoggerWindow::mainWidget;
QPushButton* LoggerWindow::pbClear, * LoggerWindow::pbClose;
QTextEdit* LoggerWindow::pLogDisplayer;
QHBoxLayout* LoggerWindow::phLayout;
QVBoxLayout* LoggerWindow::pvLayout;

void LoggerWindow::setUp(void)
{
    this->setObjectName("LoggerWindow");
    this->setFixedSize({ 640, 480 });

    this->mainWidget = new QWidget(this);
    this->mainWidget->setObjectName("LoggerMainWidget");

    this->setCentralWidget(this->mainWidget);

    this->pLogDisplayer = new QTextEdit(this->mainWidget);
    this->pLogDisplayer->setObjectName("LogText");
    // this->pLogDisplayer->setDisabled(true);
    this->pLogDisplayer->setReadOnly(true);
    this->pvLayout = new QVBoxLayout(this->mainWidget);
    this->pvLayout->setObjectName("logVLayout");

    this->pvLayout->addWidget(this->pLogDisplayer);

    this->pbClear = new QPushButton(this->mainWidget);
    this->pbClear->setObjectName("pbClear");
    this->pbClear->setText(tr("clear"));
    this->pbClose = new QPushButton(this->mainWidget);
    this->pbClose->setObjectName("pbClose");
    this->pbClose->setText(tr("close"));

    this->phLayout = new QHBoxLayout(this->mainWidget);
    this->phLayout->setObjectName("logHLayput");
    this->phLayout->addWidget(this->pbClear);
    this->phLayout->addWidget(this->pbClose);

    this->pvLayout->addLayout(this->phLayout);

    this->mainWidget->setLayout(this->pvLayout);

    this->setWindowTitle(tr("Log Window"));

    connect(this->pbClose, &QPushButton::clicked, this, &LoggerWindow::hide);
    connect(this->pbClear, &QPushButton::clicked, this->pLogDisplayer, &QTextEdit::clear);
}

void LoggerWindow::addLog(const char* fmt, ...)
{
    va_list list;
    va_start(list, fmt);
    char buf[256];
    
    vsnprintf(buf, sizeof(buf), fmt, list);
    buf[255] = 0;
    LoggerWindow::pLogDisplayer->append(buf);
    qDebug("%s", buf);

    va_end(list);
}
